<template>
    <div class="study-page">
        <h1 class="page-title">
            <BookOutlined />
            学习管理
        </h1>

        <!-- 用户信息和统计区域 -->
        <a-row :gutter="24" class="info-row">
            <a-col :span="12">
                <!-- 快速操作区域 -->
                <a-card title="快速操作" class="quick-actions-card" :bordered="false">
                    <template #extra>
                        <RocketOutlined />
                    </template>
                    <div class="quick-actions">
                        <a-button type="primary" @click="showCreateModal" size="large" class="action-btn">
                            <template #icon>
                                <PlusOutlined />
                            </template>
                            新增学习记录
                        </a-button>
                        <a-button @click="refreshStudies" size="large" class="action-btn">
                            <template #icon>
                                <ReloadOutlined />
                            </template>
                            刷新列表
                        </a-button>
                        <!-- 导出下拉菜单 -->
                        <a-dropdown>
                            <template #overlay>
                                <a-menu @click="handleExportMenuClick">
                                    <a-menu-item key="excel-simple">
                                        <FileExcelOutlined />
                                        导出为Excel（简洁版）
                                    </a-menu-item>
                                    <a-menu-item key="excel-beautiful">
                                        <FileTextOutlined />
                                        导出为Excel（精美版）
                                    </a-menu-item>
                                    <a-menu-item key="csv">
                                        <FileTextOutlined />
                                        导出为CSV
                                    </a-menu-item>
                                    <a-menu-item key="with-filters">
                                        <FilterOutlined />
                                        筛选后导出
                                    </a-menu-item>
                                    <a-menu-item key="current-page">
                                        <FileOutlined />
                                        仅导出当前页
                                    </a-menu-item>
                                    <a-menu-item key="all-data">
                                        <DatabaseOutlined />
                                        导出全部数据
                                    </a-menu-item>
                                </a-menu>
                            </template>
                            <a-button size="large" class="action-btn">
                                <template #icon>
                                    <ExportOutlined />
                                </template>
                                导出数据
                                <DownOutlined />
                            </a-button>
                        </a-dropdown>
                    </div>
                </a-card>
            </a-col>

            <a-col :span="12">
                <!-- 统计信息区域 -->
                <a-card title="学习统计" class="stats-card" :bordered="false">
                    <template #extra>
                        <BarChartOutlined />
                    </template>
                    <StudyStatsAsync :total-studies="pagination.total" :today-studies="getTodayStudies()"
                        :recently-updated="getRecentlyUpdated()" />
                </a-card>
            </a-col>
        </a-row>

        <!-- 学习记录列表 -->
        <a-card title="我的学习记录" class="studies-card" :bordered="false">
            <template #extra>
                <a-space>
                    <a-tooltip title="刷新列表">
                        <ReloadOutlined @click="refreshStudies" />
                    </a-tooltip>
                    <a-tooltip title="新增学习记录">
                        <PlusCircleOutlined @click="showCreateModal" />
                    </a-tooltip>
                    <a-tooltip title="导出数据">
                        <a-dropdown :trigger="['click']">
                            <a-button type="text" size="small">
                                <ExportOutlined />
                            </a-button>
                            <template #overlay>
                                <a-menu @click="handleExportMenuClick">
                                    <a-menu-item key="excel-simple">
                                        <FileExcelOutlined />
                                        导出Excel
                                    </a-menu-item>
                                    <a-menu-item key="current-page">
                                        <FileOutlined />
                                        导出当前页
                                    </a-menu-item>
                                </a-menu>
                            </template>
                        </a-dropdown>
                    </a-tooltip>
                </a-space>
            </template>

            <div class="table-container">
                <a-table :columns="columns" :data-source="studies" :loading="loading" :pagination="false" row-key="id"
                    size="middle" :scroll="{ x: 1200 }">
                    <template #bodyCell="{ column, record }">
                        <template v-if="column.key === 'actions'">
                            <a-space>
                                <a-tooltip title="编辑">
                                    <a-button type="link" @click="showEditModal(record)" size="small">
                                        <EditOutlined />
                                    </a-button>
                                </a-tooltip>
                                <a-tooltip title="删除">
                                    <a-popconfirm title="确定要删除这条学习记录吗？" @confirm="deleteStudy(record.id)">
                                        <a-button type="link" danger size="small">
                                            <DeleteOutlined />
                                        </a-button>
                                    </a-popconfirm>
                                </a-tooltip>
                                <a-tooltip title="查看详情">
                                    <a-button type="link" size="small" @click="showDetailModal(record)">
                                        <EyeOutlined />
                                    </a-button>
                                </a-tooltip>
                                <a-tooltip title="快速导出">
                                    <a-button type="link" size="small" @click="exportSingleStudy(record)">
                                        <ExportOutlined />
                                    </a-button>
                                </a-tooltip>
                            </a-space>
                        </template>
                        <template v-else-if="column.key === 'createdAt'">
                            <ClockCircleOutlined />
                            {{ formatDate(record.createdAt) }}
                        </template>
                        <template v-else-if="column.key === 'updatedAt'">
                            <SyncOutlined />
                            {{ formatDate(record.updatedAt) }}
                        </template>
                        <template v-else-if="column.key === 'type'">
                            <a-tag :color="getTypeColor(record.type)" class="type-tag">
                                {{ record.type }}
                            </a-tag>
                        </template>
                        <template v-else-if="column.key === 'interviewFrequency'">
                            <span v-if="record.interviewFrequency">
                                {{ record.interviewFrequency }}次/周
                            </span>
                            <span v-else class="no-data">未设置</span>
                        </template>
                        <template v-else-if="column.key === 'content'">
                            <div class="content-preview">
                                {{ record.content.length > 50 ? record.content.substring(0, 50) + '...' : record.content }}
                            </div>
                        </template>
                        <template v-else-if="column.key === 'applicationScenario'">
                            <div class="scenario-preview">
                                {{ record.applicationScenario }}
                            </div>
                        </template>
                        <template v-else-if="column.key === 'remark'">
                            <span class="remark-text">{{ record.remark || '无备注' }}</span>
                        </template>
                    </template>
                </a-table>
            </div>

            <!-- 分页组件 -->
            <div class="pagination-container">
                <a-pagination v-model:current="pagination.current" v-model:pageSize="pagination.pageSize"
                    :total="pagination.total" show-size-changer show-quick-jumper :show-total="total => `共 ${total} 条学习记录`"
                    @change="handlePageChange" @showSizeChange="handleSizeChange" />
            </div>
        </a-card>

        <!-- 学习记录模态框 - 统一处理查看、编辑、新增 -->
        <StudyModalAsync v-model:visible="modalVisible" :is-editing="isEditing" :is-viewing="isViewing"
            :editing-data="editingData" :loading="editLoading" @submit="handleModalSubmit" @cancel="handleModalCancel"
            @edit="handleEditFromView" />

        <!-- 导出筛选模态框 -->
        <a-modal v-model:visible="exportFilterVisible" title="筛选导出" @ok="handleExportWithFilters"
            @cancel="exportFilterVisible = false">
            <a-form layout="vertical">
                <a-form-item label="开始日期">
                    <a-date-picker v-model:value="exportFilters.startDate" style="width: 100%" />
                </a-form-item>
                <a-form-item label="结束日期">
                    <a-date-picker v-model:value="exportFilters.endDate" style="width: 100%" />
                </a-form-item>
                <a-form-item label="学习类型">
                    <a-select v-model:value="exportFilters.type" placeholder="请选择学习类型">
                        <a-select-option value="前端">前端</a-select-option>
                        <a-select-option value="后端">后端</a-select-option>
                        <a-select-option value="数据库">数据库</a-select-option>
                        <a-select-option value="算法">算法</a-select-option>
                        <a-select-option value="运维">运维</a-select-option>
                        <a-select-option value="测试">测试</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="关键词搜索">
                    <a-input v-model:value="exportFilters.keyword" placeholder="输入关键词搜索内容、应用场景或备注" />
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script setup lang="ts">
import { message } from 'ant-design-vue'
import {
    BookOutlined,
    PlusOutlined,
    PlusCircleOutlined,
    EditOutlined,
    DeleteOutlined,
    ReloadOutlined,
    ExportOutlined,
    BarChartOutlined,
    EyeOutlined,
    ClockCircleOutlined,
    SyncOutlined,
    RocketOutlined,
    FileExcelOutlined,
    FileTextOutlined,
    FilterOutlined,
    DownOutlined,
    FileOutlined,
    DatabaseOutlined
} from '@ant-design/icons-vue'

// 使用异步组件
const StudyModalAsync = defineAsyncComponent(() => import('~/components/modals/StudyModal.vue'))
const StudyStatsAsync = defineAsyncComponent(() => import('~/components/StudyStats.vue'))

interface Study {
    id: number
    content: string
    type: string
    applicationScenario: string
    interviewFrequency?: number
    remark?: string
    createdAt: string
    updatedAt: string
    userId: number
}

interface Pagination {
    current: number
    pageSize: number
    total: number
}

interface ExportFilters {
    startDate?: string
    endDate?: string
    type?: string
    keyword?: string
}

const authStore = useAuthStore()
const studies = ref<Study[]>([])
const loading = ref(false)

// 模态框状态 - 统一管理
const modalVisible = ref(false)
const isEditing = ref(false)
const isViewing = ref(false)
const editingData = ref<Partial<Study>>({})
const editLoading = ref(false)

// 导出相关状态
const exportFilterVisible = ref(false)
const exportFilters = reactive<ExportFilters>({})
const exportLoading = ref(false)

// 分页配置
const pagination = reactive<Pagination>({
    current: 1,
    pageSize: 10,
    total: 0
})

// 表格列配置
const columns = [
    {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        width: 60,
        fixed: 'left'
    },
    {
        title: '学习内容',
        dataIndex: 'content',
        key: 'content',
        width: 200,
        ellipsis: true
    },
    {
        title: '学习类型',
        dataIndex: 'type',
        key: 'type',
        width: 100
    },
    {
        title: '应用场景',
        dataIndex: 'applicationScenario',
        key: 'applicationScenario',
        width: 150
    },
    {
        title: '面试频率',
        dataIndex: 'interviewFrequency',
        key: 'interviewFrequency',
        width: 100
    },
    {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',
        width: 120,
        ellipsis: true
    },
    {
        title: '创建时间',
        dataIndex: 'createdAt',
        key: 'createdAt',
        width: 120
    },
    {
        title: '更新时间',
        dataIndex: 'updatedAt',
        key: 'updatedAt',
        width: 120
    },
    {
        title: '操作',
        key: 'actions',
        width: 150,
        fixed: 'right'
    }
]

// 获取学习记录列表
const fetchStudies = async () => {
    loading.value = true
    try {
        const token = authStore.token
        const currentUser = authStore.currentUser

        if (!token || !currentUser) {
            message.error('请先登录')
            return
        }

        const response = await $fetch('/api/studies', {
            headers: {
                'Authorization': `Bearer ${token}`
            },
            query: {
                username: currentUser.username,
                page: pagination.current,
                limit: pagination.pageSize
            }
        })

        if (response.code === 200) {
            studies.value = response.data.studies || []
            pagination.total = response.data.pagination?.totalCount || studies.value.length
        }
    } catch (error: any) {
        console.error('获取学习记录失败:', error)
        message.error(error.data?.message || '获取学习记录失败')
    } finally {
        loading.value = false
    }
}

// 获取所有学习记录（用于导出全部数据）
const fetchAllStudies = async (): Promise<Study[]> => {
    try {
        const token = authStore.token
        const currentUser = authStore.currentUser

        if (!token || !currentUser) {
            message.error('请先登录')
            return []
        }

        const response = await $fetch('/api/studies/all', {
            headers: {
                'Authorization': `Bearer ${token}`
            },
            query: {
                username: currentUser.username
            }
        })

        if (response.code === 200) {
            return response.data.studies || []
        }
        return []
    } catch (error: any) {
        console.error('获取全部学习记录失败:', error)
        message.error(error.data?.message || '获取全部学习记录失败')
        return []
    }
}

// 处理导出菜单点击
const handleExportMenuClick = async ({ key }: { key: string }) => {
    try {
        switch (key) {
            case 'excel-simple':
                await exportAsExcel(studies.value)
                break
            case 'excel-beautiful':
                await exportWithBeautifulStyle(studies.value)
                break
            case 'csv':
                await exportAsCSV(studies.value)
                break
            case 'with-filters':
                exportFilterVisible.value = true
                break
            case 'current-page':
                await exportCurrentPage()
                break
            case 'all-data':
                await exportAllData()
                break
            default:
                break
        }
    } catch (error) {
        console.error('导出操作失败:', error)
        message.error('导出操作失败')
    }
}

// 导出当前页数据
const exportCurrentPage = async () => {
    try {
        exportLoading.value = true
        message.loading('正在导出当前页数据...', 0)

        // 使用composables中的导出函数
        const result = await exportStudiesToExcel(studies.value, {
            filename: `学习记录_第${pagination.current}页_${new Date().toISOString().split('T')[0]}`,
            format: 'xlsx'
        })

        if (result.success) {
            message.success(`成功导出 ${studies.value.length} 条记录`)
        } else {
            message.error(result.message)
        }
    } catch (error) {
        console.error('导出当前页失败:', error)
        message.error('导出当前页失败')
    } finally {
        exportLoading.value = false
        message.destroy()
    }
}

// 导出全部数据
const exportAllData = async () => {
    try {
        exportLoading.value = true
        const hideMessage = message.loading('正在获取全部数据并导出...', 0)

        const allStudies = await fetchAllStudies()

        if (allStudies.length === 0) {
            message.warning('没有数据可导出')
            return
        }

        // 使用composables中的导出函数
        const result = await exportStudiesToExcel(allStudies, {
            filename: `全部学习记录_${new Date().toISOString().split('T')[0]}`,
            format: 'xlsx'
        })

        hideMessage()

        if (result.success) {
            message.success(`成功导出全部 ${allStudies.length} 条记录`)
        } else {
            message.error(result.message)
        }
    } catch (error) {
        console.error('导出全部数据失败:', error)
        message.error('导出全部数据失败')
    } finally {
        exportLoading.value = false
    }
}

// 处理筛选导出
const handleExportWithFilters = async () => {
    try {
        exportLoading.value = true
        message.loading('正在根据筛选条件导出数据...', 0)

        const allStudies = await fetchAllStudies()

        // 应用筛选条件
        let filteredData = allStudies.filter(study => {
            let include = true

            // 日期筛选
            if (exportFilters.startDate) {
                const start = new Date(exportFilters.startDate)
                include = include && new Date(study.createdAt) >= start
            }

            if (exportFilters.endDate) {
                const end = new Date(exportFilters.endDate)
                end.setHours(23, 59, 59, 999)
                include = include && new Date(study.createdAt) <= end
            }

            // 类型筛选
            if (exportFilters.type) {
                include = include && study.type === exportFilters.type
            }

            // 关键词筛选
            if (exportFilters.keyword) {
                const keyword = exportFilters.keyword.toLowerCase()
                include = include && (
                    study.content.toLowerCase().includes(keyword) ||
                    study.applicationScenario.toLowerCase().includes(keyword) ||
                    (study.remark && study.remark.toLowerCase().includes(keyword))
                )
            }

            return include
        })

        if (filteredData.length === 0) {
            message.warning('没有符合筛选条件的数据')
            return
        }

        // 使用composables中的导出函数
        const result = await exportStudiesToExcel(filteredData, {
            filename: `筛选后的学习记录_${new Date().toISOString().split('T')[0]}`,
            format: 'xlsx'
        })

        if (result.success) {
            message.success(`成功导出 ${filteredData.length} 条筛选记录`)
            exportFilterVisible.value = false
            // 重置筛选条件
            Object.assign(exportFilters, {})
        } else {
            message.error(result.message)
        }
    } catch (error) {
        console.error('筛选导出失败:', error)
        message.error('筛选导出失败')
    } finally {
        exportLoading.value = false
        message.destroy()
    }
}

// 导出单个学习记录
const exportSingleStudy = async (study: Study) => {
    try {
        // 使用composables中的导出函数
        const result = await exportStudiesToExcel([study], {
            filename: `学习记录_${study.id}_${new Date().toISOString().split('T')[0]}`,
            format: 'xlsx'
        })

        if (result.success) {
            message.success('学习记录导出成功')
        } else {
            message.error(result.message)
        }
    } catch (error) {
        console.error('导出单个记录失败:', error)
        message.error('导出单个记录失败')
    }
}

const showCreateModal = () => {
    isEditing.value = false
    isViewing.value = false
    editingData.value = {}
    modalVisible.value = true
}

// 显示编辑模态框
const showEditModal = (record: Study) => {
    isEditing.value = true
    isViewing.value = false
    editingData.value = { ...record }
    modalVisible.value = true
}

// 显示查看详情模态框
const showDetailModal = (record: Study) => {
    isEditing.value = false
    isViewing.value = true
    editingData.value = { ...record }
    modalVisible.value = true
}

// 处理模态框提交
const handleModalSubmit = async (submitData: any) => {
    try {
        editLoading.value = true
        const token = authStore.token
        const currentUser = authStore.currentUser

        if (!token || !currentUser) {
            message.error('请先登录')
            return
        }

        const requestData = {
            username: currentUser.username,
            content: submitData.content,
            type: submitData.type,
            applicationScenario: submitData.applicationScenario,
            interviewFrequency: submitData.interviewFrequency,
            remark: submitData.remark
        }

        if (isEditing.value && submitData.id) {
            // 更新操作
            await $fetch(`/api/studies/${submitData.id}`, {
                method: 'PUT',
                headers: {
                    'Authorization': `Bearer ${token}`
                },
                body: requestData
            })
            message.success('学习记录更新成功')
        } else {
            // 新增操作
            await $fetch('/api/studies', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`
                },
                body: requestData
            })
            message.success('学习记录创建成功')
        }

        modalVisible.value = false
        fetchStudies() // 刷新列表
    } catch (error: any) {
        console.error('操作失败:', error)
        message.error(error.data?.message || '操作失败')
    } finally {
        editLoading.value = false
    }
}

// 处理模态框取消
const handleModalCancel = () => {
    modalVisible.value = false
    editingData.value = {}
    isViewing.value = false
}

// 从查看模式切换到编辑模式
const handleEditFromView = () => {
    isViewing.value = false
    isEditing.value = true
    // 保持模态框打开状态，直接切换到编辑模式
}
// 获取学习类型颜色
const getTypeColor = (type: string) => {
    const colorMap: { [key: string]: string } = {
        '前端': 'blue',
        '后端': 'green',
        '数据库': 'orange',
        '算法': 'red',
        '运维': 'purple',
        '测试': 'cyan'
    }
    return colorMap[type] || 'default'
}

// 格式化日期
const formatDate = (dateString: string) => {
    if (!dateString) return '未知'
    return new Date(dateString).toLocaleDateString('zh-CN')
}

// 获取今日新增学习记录
const getTodayStudies = () => {
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    return studies.value.filter(study => {
        const studyDate = new Date(study.createdAt)
        return studyDate >= today
    }).length
}

// 获取最近更新的学习记录
const getRecentlyUpdated = () => {
    const weekAgo = new Date()
    weekAgo.setDate(weekAgo.getDate() - 7)
    return studies.value.filter(study => {
        const studyDate = new Date(study.updatedAt)
        return studyDate >= weekAgo
    }).length
}

// 分页处理
const handlePageChange = (page: number, pageSize?: number) => {
    pagination.current = page
    if (pageSize) {
        pagination.pageSize = pageSize
    }
    fetchStudies()
}

const handleSizeChange = (current: number, size: number) => {
    pagination.current = 1
    pagination.pageSize = size
    fetchStudies()
}

// 页面加载时获取数据
onMounted(() => {
    if (authStore.isAuthenticated) {
        fetchStudies()
    }
})

// 监听认证状态变化
watch(() => authStore.isAuthenticated, (newVal) => {
    if (newVal) {
        fetchStudies()
    }
})

useHead({
    title: '学习管理 - 系统控制台'
})
</script>

<style scoped>
/* 保持原有样式不变 */
.study-page {
    min-height: 100vh;
    padding: 24px;
    background-image: url('~/assets/images/bgcar.jpg');
    background-size: cover;
    background-position: center;
    background-attachment: fixed;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.page-title {
    text-align: center;
    color: #fff;
    font-size: 2.5rem;
    margin-bottom: 32px;
    text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12px;
}

.info-row {
    margin-bottom: 24px;
}

.quick-actions-card,
.stats-card,
.studies-card {
    margin-bottom: 0;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(10px);
    background: rgba(255, 255, 255, 0.95);
    height: 100%;
}

.quick-actions-card :deep(.ant-card-head),
.stats-card :deep(.ant-card-head),
.studies-card :deep(.ant-card-head) {
    border-bottom: 1px solid #e8e8e8;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 12px 12px 0 0;
}

.quick-actions-card :deep(.ant-card-extra),
.stats-card :deep(.ant-card-extra),
.studies-card :deep(.ant-card-extra) {
    color: white;
}

.quick-actions {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
}

.action-btn {
    height: 40px;
    font-size: 14px;
    border-radius: 6px;
}

.table-container {
    margin: 16px 0;
}

.type-tag {
    font-weight: bold;
}

.content-preview {
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
}

.scenario-preview {
    max-width: 150px;
    overflow: hidden;
    text-overflow: ellipsis;
}

.remark-text {
    color: #666;
    font-style: italic;
}

.no-data {
    color: #999;
    font-style: italic;
}

.pagination-container {
    margin-top: 16px;
    display: flex;
    justify-content: center;
}

/* 响应式设计 */
@media (max-width: 1200px) {
    .study-page {
        padding: 16px;
    }

    .info-row .ant-col-12 {
        width: 100%;
        margin-bottom: 16px;
    }
}

@media (max-width: 768px) {
    .page-title {
        font-size: 2rem;
        margin-bottom: 24px;
    }

    .quick-actions {
        flex-direction: column;
    }

    .action-btn {
        width: 100%;
    }

    .table-container {
        overflow-x: auto;
    }
}

/* 导出按钮样式 */
.export-dropdown .action-btn {
    display: flex;
    align-items: center;
    gap: 4px;
}

/* 加载状态样式 */
.export-loading {
    display: inline-flex;
    align-items: center;
    gap: 8px;
}
</style>